<template>
  <div class="query-page">
    <h1>威跃汽车销售  主播在安徽宿州</h1>
    <div class="query-form-container">
      <div class="form-row">
        <label class="label-title">品牌</label>
        <div class="input-container">
          <div v-if="!editingFields.brand" @click="enableEdit('brand')" class="display-value">
            {{ formData.brand || '' }}
          </div>
          <div class="input-wrapper" v-else>
            <input 
              v-model="formData.brand" 
              @blur="handleBrandBlur"
              @keyup.enter="handleBrandBlur"
              ref="brandInput"
              placeholder=""
              class="edit-input"
              list="brands"
            />
            <datalist id="brands">
              <option v-for="brand in brandSuggestions" :key="brand" :value="brand" />
            </datalist>
          </div>
        </div>
      </div>
      
      <div class="form-row">
        <label  class="label-title">配置</label>
        <div class="input-container">
          <div v-if="!editingFields.config" @click="enableEdit('config')" class="display-value">
            {{ formData.config || '' }}
          </div>
          <div class="input-wrapper" v-else>
            <select
              v-model="formData.config"
              @change="handleConfigChange"
              ref="configInput"
              class="edit-input select-input"
              :disabled="!formData.brand"
            >
              <option value="">请选择配置</option>
              <option v-for="config in configSuggestions" :key="config" :value="config">
                {{ config }}
              </option>
            </select>
          </div>
        </div>
      </div>
      
      <!-- 其他字段保持不变 -->
      <div class="form-row">
        <label  class="label-title">指导价</label>
        <div class="input-container">
          <div v-if="!editingFields.guidePrice" @click="enableEdit('guidePrice')" class="display-value">
            {{ formData.guidePrice || '' }}
          </div>
          <div class="input-wrapper" v-else>
            <input 
              v-model="formData.guidePrice" 
              @blur="disableEdit('guidePrice')"
              @keyup.enter="disableEdit('guidePrice')"
              ref="guidePriceInput"
              placeholder=""
              class="edit-input"
            />
          </div>
        </div>
      </div>
      
      <div class="form-row">
        <label class="discount label-title" >近期优惠</label>
        <div class="input-container" style="background-color: yellow;">
          <div v-if="!editingFields.recentDiscount" @click="enableEdit('recentDiscount')" class="display-value discount">
            {{ formData.recentDiscount || '' }}
          </div>
          <div class="input-wrapper" v-else>
            <input 
              v-model="formData.recentDiscount" 
              @blur="disableEdit('recentDiscount')"
              @keyup.enter="disableEdit('recentDiscount')"
              ref="recentDiscountInput"
              placeholder=""
              class="edit-input"
            />
          </div>
        </div>
      </div>
      
      <div class="form-row">
        <label class="label-title">裸车</label>
        <div class="input-container">
          <div v-if="!editingFields.nakedCarPrice" @click="enableEdit('nakedCarPrice')" class="display-value">
            {{ formData.nakedCarPrice || '' }}
          </div>
          <div class="input-wrapper" v-else>
            <input 
              v-model="formData.nakedCarPrice" 
              @blur="disableEdit('nakedCarPrice')"
              @keyup.enter="disableEdit('nakedCarPrice')"
              ref="nakedCarPriceInput"
              placeholder=""
              class="edit-input"
            />
          </div>
        </div>
      </div>
      
      <div class="form-row">
        <label class="label-title">险费</label>
        <div class="input-container">
          <div v-if="!editingFields.insuranceFee" @click="enableEdit('insuranceFee')" class="display-value">
            {{ formData.insuranceFee || '' }}
          </div>
          <div class="input-wrapper" v-else>
            <input 
              v-model="formData.insuranceFee" 
              @blur="disableEdit('insuranceFee')"
              @keyup.enter="disableEdit('insuranceFee')"
              ref="insuranceFeeInput"
              placeholder=""
              class="edit-input"
            />
          </div>
        </div>
      </div>
      
      <div class="form-row">
        <label class="label-title">购置</label>
        <div class="input-container">
          <div v-if="!editingFields.purchaseTax" @click="enableEdit('purchaseTax')" class="display-value">
            {{ formData.purchaseTax || '' }}
          </div>
          <div class="input-wrapper" v-else>
            <input 
              v-model="formData.purchaseTax" 
              @blur="disableEdit('purchaseTax')"
              @keyup.enter="disableEdit('purchaseTax')"
              ref="purchaseTaxInput"
              placeholder=""
              class="edit-input"
            />
          </div>
        </div>
      </div>
      
      <div class="form-row">
        <label class="label-title">上牌</label>
        <div class="input-container">
          <div v-if="!editingFields.licenseFee" @click="enableEdit('licenseFee')" class="display-value">
            {{ formData.licenseFee || '' }}
          </div>
          <div class="input-wrapper" v-else>
            <input 
              v-model="formData.licenseFee" 
              @blur="disableEdit('licenseFee')"
              @keyup.enter="disableEdit('licenseFee')"
              ref="licenseFeeInput"
              placeholder=""
              class="edit-input"
            />
          </div>
        </div>
      </div>
      
      <div class="form-row">
        <label class="full-price label-title" >全款落地</label>
        <div class="input-container" style="background-color: yellow;">
          <div v-if="!editingFields.fullPrice" @click="enableEdit('fullPrice')" class="display-value full-price">
            {{ formData.fullPrice || '' }}
          </div>
          <div class="input-wrapper" v-else>
            <input 
              v-model="formData.fullPrice" 
              @blur="disableEdit('fullPrice')"
              @keyup.enter="disableEdit('fullPrice')"
              ref="fullPriceInput"
              placeholder=""
              class="edit-input"
            />
          </div>
        </div>
      </div>
    </div>
    <div class="loan-section">
      <div class="loan-table-container">
        <table class="loan-table">
          <thead>
            <tr>
              <th>输入首付</th>
              <th>贷款金额</th>
              <th>年期</th>
              <th>年利率</th>
              <th>每月还款额</th>
              <th>总利息</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td class="td-input">
                <div v-if="!editingFields.downPayment" @click="enableEdit('downPayment')" class="display-value">
                  <span>{{ formData.downPayment || '' }}</span>
                </div>
                <div v-else class="edit-container">
                  <input 
                    v-model="formData.downPayment" 
                    @blur="disableEdit('downPayment')"
                    @keyup.enter="disableEdit('downPayment')"
                    ref="downPaymentInput"
                    placeholder=""
                    class="edit-input"
                  />
                </div>
              </td>
              <td class="td-input" >
                <div v-if="!editingFields.loanAmount" @click="enableEdit('loanAmount')" class="display-value">
                  <span>{{ formData.loanAmount || '' }}</span>
                </div>
                <div v-else class="edit-container">
                  <input 
                    v-model="formData.loanAmount" 
                    @blur="disableEdit('loanAmount')"
                    @keyup.enter="disableEdit('loanAmount')"
                    ref="loanAmountInput"
                    placeholder=""
                    class="edit-input"
                  />
                </div>
              </td>
              <td class="td-input">
                <div v-if="!editingFields.loanTerm" @click="enableEdit('loanTerm')" class="display-value">
                  <span>{{ formData.loanTerm || '' }}</span>
                </div>
                <div v-else class="edit-container">
                  <input 
                    v-model="formData.loanTerm" 
                    @blur="disableEdit('loanTerm')"
                    @keyup.enter="disableEdit('loanTerm')"
                    ref="loanTermInput"
                    placeholder=""
                    class="edit-input"
                  />
                </div>
              </td>
              <td>
                <div v-if="!editingFields.interestRate" @click="enableEdit('interestRate')" class="display-value">
                  <span>{{ formData.interestRate || '' }}</span><span class="unit">%</span>
                </div>
                <div v-else class="edit-container">
                  <input 
                    v-model="formData.interestRate" 
                    @blur="disableEdit('interestRate')"
                    @keyup.enter="disableEdit('interestRate')"
                    ref="interestRateInput"
                    placeholder=""
                    class="edit-input"
                  /><span class="unit">%</span>
                </div>
              </td>
              <td>
                <!-- 每月还款额自动计算显示 -->
                <div class="display-value">
                  <span>{{ monthlyPaymentComputed || '0.00' }}</span>
                </div>
              </td>
              <td>
                <!-- 总利息自动计算显示 -->
                <div class="display-value">
                  <span>{{ totalInterestComputed || '0.00' }}</span>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</template>

<script>
import { getBrands, getBrandByName, getConfigByBrandAndName } from '@/services/api';

export default {
  name: 'QueryView',
  data() {
    return {
      formData: {
        brand: '',
        config: '',
        guidePrice: '',
        recentDiscount: '',
        nakedCarPrice: '',
        insuranceFee: '',
        purchaseTax: '',
        licenseFee: '',
        fullPrice: '',
        downPayment: '',
        loanAmount: '',
        loanTerm: '',
        interestRate: '',
        monthlyPayment: '',
        totalInterest: ''
      },
      editingFields: {
        brand: false,
        config: false,
        guidePrice: false,
        recentDiscount: false,
        nakedCarPrice: false,
        insuranceFee: false,
        purchaseTax: false,
        licenseFee: false,
        fullPrice: false,
        downPayment: false,
        loanAmount: false,
        loanTerm: false,
        interestRate: false,
        monthlyPayment: false,
        totalInterest: false
      },
      brands: [],
      brandSuggestions: [],
      configSuggestions: []
    };
  },
  computed: {
    // 计算每月还款额
    monthlyPaymentComputed() {
      const loanAmount = parseFloat(this.formData.loanAmount) || 0;
      // 处理年利率，将其转换为小数形式
      let annualInterestRate = parseFloat(this.formData.interestRate) || 0;
      // 将百分比转换为小数形式（例如 1.5 转换为 0.015）
      annualInterestRate = annualInterestRate / 100;
      const loanTermYears = parseFloat(this.formData.loanTerm) || 0;
      
      // 如果贷款金额、利率或期限为0，返回0
      if (loanAmount <= 0 || annualInterestRate <= 0 || loanTermYears <= 0) {
        return '0.00';
      }
      
      // 月利率
      const monthlyInterestRate = annualInterestRate / 12;
      // 还款月数
      const numberOfPayments = loanTermYears * 12;
      
      // 等额本息还款计算公式
      // M = P * [r(1+r)^n] / [(1+r)^n - 1]
      // M: 每月还款额
      // P: 贷款本金
      // r: 月利率
      // n: 还款月数
      
      if (monthlyInterestRate === 0) {
        // 如果利率为0，直接计算
        return (loanAmount / numberOfPayments).toFixed(2);
      }
      
      const monthlyPayment = 
        (loanAmount * monthlyInterestRate * Math.pow(1 + monthlyInterestRate, numberOfPayments)) / 
        (Math.pow(1 + monthlyInterestRate, numberOfPayments) - 1);
      
      return monthlyPayment.toFixed(2);
    },
    
    // 计算总利息
    totalInterestComputed() {
      const loanAmount = parseFloat(this.formData.loanAmount) || 0;
      const loanTermYears = parseFloat(this.formData.loanTerm) || 0;
      const monthlyPayment = parseFloat(this.monthlyPaymentComputed) || 0;
      
      // 如果贷款金额、期限或月还款额为0，返回0
      if (loanAmount <= 0 || loanTermYears <= 0 || monthlyPayment <= 0) {
        return '0.00';
      }
      
      // 总还款额
      const totalPayment = monthlyPayment * loanTermYears * 12;
      // 总利息 = 总还款额 - 贷款本金
      const totalInterest = totalPayment - loanAmount;
      
      return totalInterest >= 0 ? totalInterest.toFixed(2) : '0.00';
    }
  },
  async mounted() {
    await this.loadBrands();
    this.extractBrandSuggestions();
  },
  methods: {
    async loadBrands() {
      try {
        const response = await getBrands();
        this.brands = response.data;
      } catch (error) {
        console.error('加载品牌信息失败:', error);
      }
    },
    extractBrandSuggestions() {
      this.brandSuggestions = this.brands.map(brand => brand.name);
    },
    async handleBrandBlur() {
      this.editingFields.brand = false;
      // 当品牌改变时，清空配置并获取新的配置列表
      if (this.formData.brand) {
        await this.loadConfigSuggestions(this.formData.brand);
        // 清空配置字段
        this.formData.config = '';
      }
    },
    async loadConfigSuggestions(brandName) {
      try {
        const response = await getBrandByName(brandName);
        const brand = response.data;
        if (brand && brand.configs) {
          this.configSuggestions = brand.configs.map(config => config.name);
        } else {
          this.configSuggestions = [];
        }
      } catch (error) {
        console.error('加载配置信息失败:', error);
        this.configSuggestions = [];
      }
    },
    handleConfigChange() {
      // 当配置选择完成后，获取完整的车辆信息
      if (this.formData.brand && this.formData.config) {
        this.loadCarDetails(this.formData.brand, this.formData.config);
      }
      // 选择后关闭编辑状态
      this.disableEdit('config');
    },
    async loadCarDetails(brandName, configName) {
      try {
        const response = await getConfigByBrandAndName(brandName, configName);
        const configData = response.data;
        // 更新表单数据
        this.formData = {
          ...this.formData,
          guidePrice: configData.guidePrice || '',
          recentDiscount: configData.recentDiscount || '',
          nakedCarPrice: configData.nakedCarPrice || '',
          insuranceFee: configData.insuranceFee || '',
          purchaseTax: configData.purchaseTax || '',
          licenseFee: configData.licenseFee || '',
          fullPrice: configData.fullPrice || '',
          downPayment: configData.downPayment || '',
          loanAmount: configData.loanAmount || '',
          loanTerm: configData.loanTerm || '',
          // 处理从后端获取的带百分号的利率数据
          interestRate: configData.interestRate ? configData.interestRate.toString().replace('%', '') : '',
          monthlyPayment: configData.monthlyPayment || '',
          totalInterest: configData.totalInterest || ''
        };
      } catch (error) {
        console.error('加载车辆详细信息失败:', error);
      }
    },
    enableEdit(field) {
      this.editingFields[field] = true;
      this.$nextTick(() => {
        const inputRef = `${field}Input`;
        if (this.$refs[inputRef]) {
          this.$refs[inputRef].focus();
        }
      });
    },
    disableEdit(field) {
      this.editingFields[field] = false;
    }
  }
};
</script>

<style scoped>
.query-page {
  max-width: 1200px;
  margin: 0 auto;
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  position: relative;
  z-index: 1;
}



h1 {
  text-align: center;
  color: red; /* 标题为红色 */
  margin-bottom: 0; /* 移除底部边距 */
  font-size: 22px; /* 标题字体大小 */
  border: 1px solid black; /* 添加边框 */
  padding: 10px;
  margin-left: -1px; /* 补偿左边框的宽度 */
  margin-right: -1px; /* 补偿右边框的宽度 */
  margin-top: -1px; /* 补偿顶部边框的宽度 */
}

h2 {
  color: #2c3e50;
  margin: 30px 0 15px 0;
  font-size: 22px; /* 贷款计算标题字体大小 */
}

.query-form-container {
  background-color: white;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
  margin-bottom: 0; /* 移除底部边距，实现无缝衔接 */
  border: 1px solid black; /* 为容器添加黑色边框 */
  border-bottom: none; /* 移除底部边框以与表格顶部边框合并 */
  border-top: none; /* 移除顶部边框以与标题底部边框合并 */
  width: 100%;
  margin-left: -1px; /* 补偿左边框的宽度 */
  margin-right: -1px; /* 补偿右边框的宽度 */
  margin-top: -1px; /* 补偿顶部边框的宽度 */
}

.form-row {
  display: flex;
  align-items: center;
  border-bottom: 1px solid black; /* 添加横线边框 */
  margin-left: -1px; /* 补偿左边框的宽度 */
  margin-right: -1px; /* 补偿右边框的宽度 */
}

.form-row:last-child {
  border-bottom: 1px solid black; /* 最后一行保留边框 */
}

.form-row label {
  width: 150px;
  font-weight: bold;
  color: #2c3e50;
  text-align: right;
  font-size: 22px; /* 字段标签字体大小 */
  border-right: 1px solid black; /* 标签右侧添加边框 */
  padding: 8px;
  margin-left: -1px; /* 补偿左边框的宽度 */

}

.form-row .discount {
  color: green;
}

.form-row .full-price {
  color: red;
}

.input-container {
  flex: 1;
  position: relative;
  display: flex;
  align-items: center;
}

.input-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  margin-right: -1px; /* 补偿右边框的宽度 */
}

.display-value {
  padding: 8px;
  cursor: pointer;
  min-height: 47px;
  font-size: 22px; /* 字段字体大小 */
  min-width: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
}



.display-value:hover {
  background-color: #f0f8ff;
}

.edit-input {
  padding: 6px 8px;
  font-size: 22px; /* 字段字体大小 */
  background-color: transparent;
  outline: none;
  width: auto;
  border: none; /* 完全移除边框 */
  box-shadow: none; /* 移除阴影 */
  text-align: center; /* 居中显示 */
}

.select-input {
  width: 100%;
  padding: 6px 8px;
  background-color: transparent;
  border: none; /* 完全移除边框 */
  box-shadow: none; /* 移除阴影 */
  font-size: 22px; /* 字段字体大小 */
  text-align: center; /* 居中显示 */
}

.unit {
  margin-left: 2px;
  white-space: nowrap;
  font-size: 22px; /* 单位字体大小 */
}

.loan-section {
  margin-top: 0; /* 移除顶部边距，实现无缝衔接 */
  margin-top: -1px; /* 通过负边距实现边框合并 */
  margin-left: -1px; /* 补偿左边框的宽度 */
  margin-right: -1px; /* 补偿右边框的宽度 */
}

.loan-table-container {
  overflow-x: auto;
  border: none; /* 移除边框 */
  padding: 0; /* 移除内边距 */
  margin: 0; /* 移除外边距 */
}

.loan-table {
  width: 100%;
  border-collapse: collapse;
  background-color: white;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
  font-size: 22px; /* 表格字体大小 */
  margin-top: 0; /* 确保无缝衔接 */
  border: 1px solid black; /* 为表格添加黑色边框 */
  border-top: none; /* 移除顶部边框以与表单底部边框合并 */
}


.loan-table th {
  background-color: #f5f5f5;
  padding: 8px;
  text-align: center;
  font-weight: bold;
  color: #2c3e50;
  border: 1px solid black; /* 为表头添加黑色边框 */
  font-size: 22px; /* 表格字体大小 */
  border-collapse: collapse;
}

.loan-table td {
  padding: 8px;
  text-align: center;
  border: 1px solid black; /* 为表格单元格添加黑色边框 */
  position: relative;
  min-width: 100px;
  border-collapse: collapse;
}

.loan-table td div {
  padding: 6px 8px;
  cursor: pointer;
  min-height: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 22px; /* 表格字体大小 */
}

.loan-table td div:hover {
  background-color: #f0f8ff;
}

.loan-table .edit-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 0;
}

.loan-table input {
  padding: 6px 8px;
  text-align: center;
  font-size: 22px; /* 表格字体大小 */
  background-color: transparent;
  outline: none;
  width: auto;
  min-width: 30px;
  border: none; /* 完全移除边框 */
  box-shadow: none; /* 移除阴影 */
}

.loan-table .unit {
  margin-left: 2px;
  white-space: nowrap;
  font-size: 22px; /* 单位字体大小 */
}

</style>